<template>
    <!-- 整体容器 -->
    <div class="pages">
        <el-container class="page-container">
            <!-- 添加 -->
            <el-header class="page-header">
                <el-form :inline="true" :model="form" class="demo-form-inline">
                    <el-form-item label="角色名称：">
                        <el-input v-model.trim="form.name" />
                    </el-form-item>
                    <el-form-item label="详情信息：">
                        <el-input v-model.trim="form.desc" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="addRole" v-direct="['sys:role:create']">添加</el-button>
                    </el-form-item>
                </el-form>
            </el-header>
            <el-main class="page-main">
                <!-- 表格 -->
                <div class="main-table">
                    <el-table :data="tableData.data" border style="width: 100%">
                        <el-table-column prop="name" label="角色名称" />
                        <el-table-column prop="desc" label="说明" />
                        <el-table-column label="操作" #default="scope">
                            <div v-if="scope.row.id != 1">
                                <el-button type="primary" @click="modifyRole(scope.row)" v-direct="['sys:role:update']">修改</el-button>
                                <el-button type="primary" @click="authRole(scope.row)" v-direct="['sys:role:permissionlist']">授权</el-button>
                                <el-button type="danger" @click="deleRole(scope.row)" v-direct="['sys:role:delete']">删除</el-button>
                            </div>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 分页 -->
                <div class="page-pagination">
                    <Pagination v-bind="roleObj" @handle-pagination="emitEntProps"/>
                </div>
                <!-- 回到顶部组件 -->
                <el-backtop :right="100" :bottom="100" target=".el-main" ref="refBacktop" />
                <!-- 对话框组件 -->
                <el-dialog v-model="dialogFormVisible" :title="dialogTitle">
                    <!-- 修改角色列表 -->
                    <template v-if="dialogHide">
                        <el-form :inline="true" :model="dialogForm" class="demo-form-inline">
                            <el-form-item label="角色名称：">
                                <el-input v-model.trim="dialogForm.name" />
                            </el-form-item>
                            <el-form-item label="详情信息：">
                                <el-input v-model.trim="dialogForm.desc" />
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="determineRole">修改</el-button>
                            </el-form-item>
                        </el-form>
                    </template>
                    <!-- 权限配置 -->
                    <template v-else>
                        <el-tree :data="rowInfo.systemPermissions" show-checkbox node-key="id" :expand-on-click-node="true" 
                        ref="tree">
                            <template #default="{ node, data }">
                                <span class="custom-tree-node">
                                    <span>{{ node.label }}</span>
                                    <span v-if="!data.children">
                                        {{data.id}}
                                    </span>
                                </span>
                            </template>
                        </el-tree>
                        <div class="config-tree">
                            <span class="dialog-footer" >
                                <el-button @click="dialogFormVisible = false">取消</el-button>
                                <el-button type="primary" @click="determineConfig">确定</el-button>
                            </span>
                        </div>
                    </template>
                </el-dialog>
            </el-main>
        </el-container>
    </div>
</template>
<script lang="ts" setup>
import { ClassPagination } from '#/index';
import { reactive, ref, nextTick, watch } from "vue";
import { get, post } from "@/utils/index";
import { ElMessage, ElMessageBox } from "element-plus";
const refBacktop = ref()
const tree = ref()//获取树形菜单实例
// 表格数据
const tableData:TypeTableData = reactive({ data:[] })
// 表单数据
let form:TypeRoleObj = reactive({
    name: '',
    desc: '',
    status: 1
})
// 请求角色管理数据
// 分页数据,父传子参数
let roleObj = reactive(new ClassPagination())
// 修改角色对话框数据
const dialogFormVisible = ref<boolean>(false)    // 对话框默认隐藏
const dialogHide = ref<boolean>(true)    //用于判断是否显示权限管理还是修改角色列表
const dialogTitle = ref<string>("修改消息") // 定义标题
const dialogForm:TypeRoleObj = reactive({   //对话框表单数据
    name: '',
    desc: '',
    status: 1,
    id: 0
})
// 权限配置数据
const rowInfo:TypeRowInfo = reactive({
    assignedPermissions:[],
    systemPermissions:[],
    roleId:0
})

// 请求角色管理列表
const initRole = () => {
    post({
        _gp: 'admin.role',
        _mt: 'list',
        ...roleObj
    }).then((res) => {
        if (200 === res.errno) {
            let { total, items } = res.data
            tableData.data = items
            roleObj.total = total
        }else{
            ElMessage.error(res.errmsg)
        }
    })
}
// 页面初次渲染
initRole()
//保留空输入框信息
let initForm = { ...form }
// 添加角色事件
const addRole = () => {
    if(form.name != ''){
        get({
        _gp: 'admin.role',
        _mt: 'create',
        role: {
            ...form
        }
    }).then((res) => {
        if (200 === res.errno) {
            ElMessage.success('添加成功')
            initRole()
            Object.assign(form, initForm)  // 清空输入框
        } else {
            ElMessage.error(res.errmsg)
        }
    })
    }else{
        ElMessage.warning('角色名称不能为空')
    }
}
// 删除角色列表
const deleRole = (row: TypeRow) => {
    ElMessageBox.confirm(
        '确认是否删除?',
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }
    ).then(() => {
        post({
            _gp: 'admin.role',
            _mt: 'delete',
            roleId: row.id
        }).then((res) => {
            if (200 === res.errno) {
                initRole()
                ElMessage.success("删除成功")
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }).catch(() => {
        ElMessage.warning("已取消删除")
    })
}
// 修改角色列表
const modifyRole = (row: TypeRow) => {
    dialogFormVisible.value = true
    dialogHide.value = true
    dialogTitle.value = "修改消息"
    dialogForm.name = row.name,
    dialogForm.desc = row.desc
    dialogForm.id = row.id
}
// 确定修改角色列表
const determineRole = () => {
    dialogFormVisible.value = false
    get({
        _gp: 'admin.role',
        _mt: 'update',
        role: {
            ...dialogForm
        }
    }).then((res) => {
        if (200 === res.errno) {
            ElMessage.success("修改成功")
            initRole()
        } else {
            ElMessage.error(res.errmsg)
        }
    })
}
// 授权角色列表
const authRole = (row: TypeRow) => {
    dialogFormVisible.value = true
    dialogHide.value = false
    dialogTitle.value = "权限配置"
    rowInfo.roleId = row.id //获取id
    post({
        _gp: 'admin.role',
        _mt: 'permissionList',
        roleId: row.id
    }).then((res) => {
        if(200 === res.errno){
            let { assignedPermissions,systemPermissions } = res.data
            rowInfo.assignedPermissions = assignedPermissions   //权限默认选中数据
            rowInfo.systemPermissions = systemPermissions   //权限数据
            // 使用nextTick延迟回调
            nextTick(()=>{
                tree.value.setCheckedKeys(rowInfo.assignedPermissions)
            })
        }
    })
}
// 确定修改权限
const determineConfig = ()=>{
    let permissions = tree.value.getCheckedKeys(true)
    post({
        _gp: 'admin.role',
        _mt: 'permissionSet',
        roleSetPermissionDTO: JSON.stringify({'roleId':rowInfo.roleId,permissions})
    }).then((res) => {
        if(200 === res.errno){
            dialogFormVisible.value = false
            initRole()
            ElMessage.success("权限修改成功")
        }else{
            ElMessage.error(res.errmsg)
        }
    })
}
/**
 * 分页组件传递过来的数据
 * @param val
 * page:页数
 * limit:条数
 */
 function emitEntProps(val: { page: number, limit: number }) {
    let paging = roleObj
    paging.page = val.page
    paging.limit = val.limit
    initRole()
}

</script>
<style lang="less" scoped>
// 对话框样式
.demo-form-inline {
    //修改角色样式
    height: 40px;
    display: flex;
    align-items: center;
}
/deep/.el-form-item,.el-form-item--default{
        margin: 0;
        padding-right: 10px;
    }
.custom-tree-node{
    display: flex;
    flex: 1;
    justify-content: space-between;
}
.config-tree {
    //配置样式
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}
</style>